import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  console.log('🌱 Seeding database...')

  // Create a default project
  const project = await prisma.project.upsert({
    where: { key: 'TAPD' },
    update: {},
    create: {
      name: 'TAPD 电子产品研发管理系统',
      key: 'TAPD',
      description: '基于Next.js的电子产品全生命周期管理平台',
      type: 'SOFTWARE',
      status: 'ACTIVE',
    },
  })

  console.log('✅ Created project:', project.name)

  // Create a default user
  const user = await prisma.user.upsert({
    where: { email: 'admin@tapd.com' },
    update: {},
    create: {
      email: 'admin@tapd.com',
      username: 'admin',
      name: '系统管理员',
      role: 'ADMIN',
    },
  })

  console.log('✅ Created user:', user.name)

  // Add user as project member
  const projectMember = await prisma.projectMember.upsert({
    where: {
      projectId_userId: {
        projectId: project.id,
        userId: user.id,
      },
    },
    update: {},
    create: {
      projectId: project.id,
      userId: user.id,
      role: 'OWNER',
    },
  })

  console.log('✅ Added user to project as owner')

  // Create a default iteration
  const iteration = await prisma.iteration.create({
    data: {
      projectId: project.id,
      name: '初始迭代',
      description: '系统初始迭代',
      startDate: new Date(),
      endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days from now
      status: 'ACTIVE',
    },
  })

  console.log('✅ Created iteration:', iteration.name)

  // Create sample requirements
  const requirements = await Promise.all([
    prisma.requirement.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        title: '实现用户认证系统',
        description: '开发完整的用户注册、登录、权限管理功能',
        type: 'FEATURE',
        priority: 'high',
        status: 'active',
        creatorId: user.id,
        estimate: 16,
      },
    }),
    prisma.requirement.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        title: '设计数据库架构',
        description: '设计并实现支持电子产品管理的数据库模型',
        type: 'FEATURE',
        priority: 'high',
        status: 'completed',
        creatorId: user.id,
        estimate: 8,
      },
    }),
    prisma.requirement.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        title: '硬件版本管理模块',
        description: '开发硬件版本的全生命周期管理功能',
        type: 'HARDWARE_FEATURE',
        priority: 'medium',
        status: 'in_progress',
        creatorId: user.id,
        estimate: 24,
      },
    }),
  ])

  console.log('✅ Created sample requirements')

  // Create sample tasks
  const tasks = await Promise.all([
    prisma.task.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        requirementId: requirements[0].id,
        title: '实现JWT认证中间件',
        description: '开发基于JWT的用户认证中间件',
        type: 'FEATURE',
        priority: 'high',
        status: 'completed',
        creatorId: user.id,
        estimate: 4,
      },
    }),
    prisma.task.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        requirementId: requirements[0].id,
        title: '设计用户界面',
        description: '设计用户注册和登录界面',
        type: 'FEATURE',
        priority: 'medium',
        status: 'in_progress',
        creatorId: user.id,
        estimate: 6,
      },
    }),
    prisma.task.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        requirementId: requirements[2].id,
        title: '硬件版本数据模型设计',
        description: '设计硬件版本管理的数据模型和关系',
        type: 'FEATURE',
        priority: 'high',
        status: 'todo',
        creatorId: user.id,
        estimate: 3,
      },
    }),
  ])

  console.log('✅ Created sample tasks')

  // Create sample bugs
  const bugs = await Promise.all([
    prisma.bug.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        requirementId: requirements[0].id,
        title: '登录页面响应式布局问题',
        description: '在移动设备上登录页面布局错乱',
        severity: 'MEDIUM',
        priority: 'medium',
        status: 'open',
        creatorId: user.id,
      },
    }),
    prisma.bug.create({
      data: {
        projectId: project.id,
        iterationId: iteration.id,
        requirementId: requirements[1].id,
        title: '数据库查询性能问题',
        description: '复杂查询响应时间过长，需要优化索引',
        severity: 'HIGH',
        priority: 'high',
        status: 'in_progress',
        creatorId: user.id,
      },
    }),
  ])

  console.log('✅ Created sample bugs')

  // Create sample hardware version
  const hardwareVersion = await prisma.hardwareVersion.create({
    data: {
      projectId: project.id,
      version: 'V1.0',
      name: '初始硬件版本',
      description: '产品初始硬件版本设计',
      status: 'DESIGN',
      creatorId: user.id,
    },
  })

  console.log('✅ Created sample hardware version')

  // Create sample BOM
  const bom = await prisma.bOM.create({
    data: {
      projectId: project.id,
      version: 'V1.0',
      name: '初始BOM清单',
      description: '产品初始物料清单',
      status: 'DRAFT',
      currency: 'CNY',
      creatorId: user.id,
    },
  })

  console.log('✅ Created sample BOM')

  // Create sample BOM items
  const bomItems = await Promise.all([
    prisma.bOMItem.create({
      data: {
        bomId: bom.id,
        partNumber: 'MCU-001',
        name: '主控芯片',
        description: 'STM32F4系列主控芯片',
        category: '芯片',
        quantity: 1,
        unit: '个',
        unitCost: 25.50,
        totalPrice: 25.50,
        manufacturer: 'STMicroelectronics',
        lifecycle: 'ACTIVE',
        leadTime: 14,
        moq: 100,
      },
    }),
    prisma.bOMItem.create({
      data: {
        bomId: bom.id,
        partNumber: 'RES-001',
        name: '贴片电阻',
        description: '0603封装10K电阻',
        category: '电阻',
        quantity: 10,
        unit: '个',
        unitCost: 0.05,
        totalPrice: 0.50,
        manufacturer: 'Yageo',
        lifecycle: 'ACTIVE',
        leadTime: 7,
        moq: 1000,
      },
    }),
  ])

  console.log('✅ Created sample BOM items')

  console.log('🎉 Database seeding completed!')
  console.log('📊 Summary:')
  console.log(`   - Project: ${project.name}`)
  console.log(`   - User: ${user.name}`)
  console.log(`   - Iteration: ${iteration.name}`)
  console.log(`   - Requirements: ${requirements.length}`)
  console.log(`   - Tasks: ${tasks.length}`)
  console.log(`   - Bugs: ${bugs.length}`)
  console.log(`   - Hardware Version: ${hardwareVersion.name}`)
  console.log(`   - BOM: ${bom.name}`)
  console.log(`   - BOM Items: ${bomItems.length}`)
}

main()
  .catch((e) => {
    console.error('❌ Error seeding database:', e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })